﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;

namespace WeighClient.Utils
{
    public class HttpServer
    {
        public static event MMSendMsg sendMsgEvent;

        private int port = 9001;//测试修改
        private HttpListener httpListener;

        public HttpServer()
        {
            this.httpListener = new HttpListener();
        }
        public HttpServer(int port)
            : this()
        {
            this.port = port;
        }
        public void Run()
        {
            this.httpListener.Prefixes.Add(string.Format("http://+:{0}/", this.port));
            this.httpListener.Start();
            this.httpListener.BeginGetContext(new AsyncCallback(GetContext), this.httpListener);
            Console.WriteLine("Listen Port:" + port);

            JObject jsonObj = new JObject();
            jsonObj.Add("type", "ServerStarted");

            SendMsg(jsonObj);
        }
        public bool IsListening()
        {
            return httpListener.IsListening;
        }
        private void GetContext(IAsyncResult ar)
        {
            HttpListener httpListener = ar.AsyncState as HttpListener;
            HttpListenerContext context = httpListener.EndGetContext(ar);  //接收到的请求context（一个环境封装体）

            httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener);  //开始 第二次 异步接收request请求

            HttpListenerRequest request = context.Request;  //接收的request数据
            HttpListenerResponse response = context.Response;  //用来向客户端发送回复

            string rawData;
            using (StreamReader reader = new StreamReader(request.InputStream))
            {
                rawData = reader.ReadToEnd();
            }
            try
            {
                JObject jsonObj = JObject.Parse(rawData);
                SendMsg(jsonObj);
            }
            catch(Exception ex)
            {

            }
            /*
            string weight = request.QueryString["weight"];
            string complete = request.QueryString["complete"];
            string gateStatus = request.QueryString["gateStatus"];
            if (!string.IsNullOrEmpty(weight))
            {
                Console.WriteLine("weight:" + weight);
                App.GetDeviceInfo().Weight = Double.Parse(weight);

                JObject resultObj = new JObject();
                resultObj.Add("type", "Weight");
                JObject resultDetailObj = new JObject();
                resultDetailObj.Add("weight", weight);
                resultObj.Add("detail", resultDetailObj);

                SendMsg(resultObj);
            }
            else if (!string.IsNullOrEmpty(complete))
            {
                JObject resultObj = new JObject();
                resultObj.Add("type", "complete");

                SendMsg(resultObj);
            }
            else if (!string.IsNullOrEmpty(gateStatus))
            {
                string inOut = request.QueryString["inOut"];
                string open = request.QueryString["open"];

                JObject resultObj = new JObject();
                resultObj.Add("type", "gateStatus");
                resultObj.Add("inOut", inOut);
                resultObj.Add("open", open);

                SendMsg(resultObj);
            }
            else
            {
                try
                {
                    string direction = request.QueryString["direction"];

                    JObject jsonObj = JObject.Parse(rawData);

                    String cameraIP = (String)jsonObj["AlarmInfoPlate"]["ipaddr"];
                    String carno = (String)jsonObj["AlarmInfoPlate"]["result"]["PlateResult"]["license"];

                    Console.WriteLine("车牌号:" + carno);

                    JObject resultObj = new JObject();
                    resultObj.Add("type", "GetCarNo");
                    resultObj.Add("direction", direction);
                    JObject resultDetailObj = new JObject();
                    resultDetailObj.Add("carNo", carno);
                    resultObj.Add("detail", resultDetailObj);

                    SendMsg(resultObj);
                    //DoorControlHelper.OpenDoor(cameraIP, carno);
                    //PortControlHelper.openDoor(2);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.GetBaseException());
                }
            }*/
            using (Stream output = response.OutputStream)  //发送回复
            {
                byte[] buffer = Encoding.UTF8.GetBytes("ok");
                output.Write(buffer, 0, buffer.Length);
            }
        }

        public void SendMsg(JObject obj)
        {
            if(sendMsgEvent != null)
            {
                sendMsgEvent(obj);
            }
        }
    }
}
